package org.light.facade;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.javaforever.gatescore.utils.StringUtil;
import org.javaforever.poitranslator.core.ProjectExcelWorkBook;
import org.light.domain.Domain;
import org.light.domain.Project;
import org.light.domain.ValidateInfo;
import org.light.exception.ValidateException;

import net.sf.json.JSONObject;

/**
 * 
 * @author Jerry Shen 2021.2.3
 *
 */
public class ParseSampleTemplateFacade extends HttpServlet {
	private static final long serialVersionUID = 5802052062671759854L;
	protected static Logger logger = Logger.getLogger(ParseSampleTemplateFacade.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ParseSampleTemplateFacade() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		InputStream input = null;
		OutputStream output = null;
		InputStream is = null;
		POIFSFileSystem fs = null;
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Map<String, Object> result = new TreeMap<String, Object>();
		// request.setCharacterEncoding("UTF-8");
		File f = null;
		try {
			String fileName = request.getParameter("fileName");
			boolean ignoreWarning = true;
			if (!StringUtil.isBlank(request.getParameter("ignoreWarning"))) ignoreWarning = "true".equalsIgnoreCase(request.getParameter("ignoreWarning"));

			String root = request.getSession().getServletContext().getRealPath("/").replace('\\', '/');

			String samplefolder = root + "spreadsheettemplates/";
			samplefolder = samplefolder.replace('\\', '/');
			String excelfolder = root + "spreadsheets/";
			excelfolder = excelfolder.replace('\\', '/');
			logger.debug("JerryDebug:excelfolder:" + excelfolder);
			
			File source = new File(samplefolder+fileName);
			f = new File(excelfolder+fileName);
			if (f.exists()) f.delete();
			Files.copy(source.toPath(), f.toPath());

			String sourcefolder = root + "source/";
			
			is = new FileInputStream(f);
			fs = new POIFSFileSystem(is);
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			ProjectExcelWorkBook pewb = new ProjectExcelWorkBook();

			Project project = pewb.pureTranslate(wb,ignoreWarning);
			project.setExcelTemplateName(f.getName());
			project.setExcelTemplateFolder(root + "spreadsheets/");

			logger.debug(sourcefolder);
			project.setFolderPath(sourcefolder);
			project.setSourceFolderPath((root + "templates/").replace('\\', '/'));
			ExcelWizardFacade.setInstance(project);

			for (Domain d:ExcelWizardFacade.getInstance().getDomains()) {
				logger.debug("domain:"+d.getStandardName());
			}
			for (List<Domain> data:ExcelWizardFacade.getInstance().getDataDomains()) {
				if (data!=null && data.size()>0) logger.debug("domain:"+data.get(0).getStandardName());
				for (Domain d:data) {
					if (d.getDomainName()!=null) logger.debug(d.getDomainName().getFieldValue()+",");
				}
				logger.debug("\n");
			}
			
			f.delete();
			result.put("success", true);
			result.put("data", null);
			out.print(JSONObject.fromObject(result));
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof ValidateException) {
				ValidateException ev = (ValidateException) e;
				result.put("success", false);
				ValidateInfo info = ev.getValidateInfo();
				List<String> compileErrors = info.getCompileErrors();
				result.put("compileErrors", compileErrors);
				List<String> compileWarnings = info.getCompileWarnings();
				result.put("compileWarnings", compileWarnings);
				out.print(JSONObject.fromObject(result));
				return;
			}
			if (!(e instanceof ValidateException)) {
				e.printStackTrace();
				result.put("success", false);
				if (e.getMessage() != null && !e.getMessage().equals("")) {
					result.put("compileErrors", new ArrayList<String>().add(e.getMessage()));
				} else {
					result.put("compileErrors", new ArrayList<String>().add("空指针或其他语法错误！"));
				}
				out.print(JSONObject.fromObject(result));
			}
		} finally {
			if (input != null)
				input.close();
			if (output != null)
				output.close();
			if (is != null)
				is.close();
			if (fs != null)
				fs.close();
			if (out != null)
				out.close();
		}
	}
}
